﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.MultiTenancy;

namespace AbpApplication_Module.MultiTenancys
{
    /// <summary>   
    ///  租户切换(租户存储)--Cookie
    /// </summary>
    [Dependency(ServiceLifetime.Singleton)]
    public class TenantSwitchAppService : IRemoteService
    {
        // 查询接口
        public ITenantStore TenantStore { set; get; }

        public IHttpContextAccessor httpContextAccessor { get; set; }

        public ICurrentTenant currentTenant { get; set; }

        public void SwitchTenant(string TanantName)
        {
            Guid? tenantId = null;
            // 1、查询租户
            if (!TanantName.IsNullOrEmpty())
            {
                var tenant = TenantStore.Find(TanantName);
                if (tenant == null)
                {
                    throw new UserFriendlyException($"{TanantName}，租户不存在");
                }

                if (!tenant.IsActive)
                {
                    throw new UserFriendlyException($"{TanantName}，租户未激活");
                }

                // 1.2、取出租户Id
                tenantId = tenant.Id;
            }

            // 2、存储租户
            MultiTenancyCookieHelper.SetTenantCookie(httpContextAccessor.HttpContext,
                    tenantId,
                    TenantResolverConsts.DefaultTenantKey);
        }

        /// <summary>
        /// 删除租户
        /// </summary>
        public void DeleteTenant()
        {
            // 1、删除租户
            MultiTenancyCookieHelper.DeleteTenantCookie(httpContextAccessor.HttpContext, TenantResolverConsts.DefaultTenantKey);

            // 2、清空当前租户信息
            using (currentTenant.Change(null))
            {
                Console.WriteLine("租户清除成功");
            }
        }
    }
}
